package com.sto.stoapp.activity.administrator.system;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.sto.stoapp.StoApplication;
import com.sto.stoapp.StoConfig;
import com.sto.stoapp.activity.R;
import com.sto.stoapp.activity.administrator.ExceptionLogListActivity;
import com.sto.stoapp.activity.administrator.hardware.AdminSoftVersionActivity;
import com.sto.stoapp.activity.scanner.business.StoTouchScreenLockSetActivity;
import com.sto.stoapp.adapter.SoleAdapter;
import com.sto.stoapp.broadcast.HomeBroadAction;
import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.entity.FunctionEntity;
import com.sto.stoapp.http.MessageType;
import com.sto.stoapp.http.response.TimeSynchResponse;
import com.sto.stoapp.listener.OnBackClickListener;
import com.sto.stoapp.listener.StoOnItemClickListener;
import com.sto.stoapp.manager.DownApk;
import com.sto.stoapp.manager.DownApk.ExceptionClickListener;
import com.sto.stoapp.thread.DeleteDataThread;
import com.sto.stoapp.thread.TimeSynchThread;
import com.sto.stoapp.util.Action;
import com.sto.stoapp.util.Helper;
import com.sto.stoapp.util.MemorySpaceCheck;
import com.sto.stoapp.widget.BaseDialog;
import com.sto.stoapp.widget.StoHomeActivity;

import java.util.ArrayList;
import java.util.List;

/**
 * 系统设置
 * 
 * @author mgf
 * 
 */
@SuppressLint("HandlerLeak")
public class AdminSystemSettingActivity extends StoHomeActivity {

	// 功能列表
	private ListView systemList;

	// 功能列表适配器
	private SoleAdapter soleAdapter;

	private List<FunctionEntity> functionList;

	private String broadType;

	// 按键映射
	private static final int[] MAPP_TO_KEY = { R.string.scanner_settings,
			R.string.back_light, R.string.synch_time,
			R.string.system_auto_close_screen, R.string.surplus_storage,
			R.string.version_infomation, R.string.software_upgrade,
			R.string.blue_settings, R.string.wlan_settings,
			R.string.keydown_sound };// R.string.exception_log,

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == MessageType.SYNCH_TIME_TYPE) {
				TimeSynchResponse response = (TimeSynchResponse) msg.obj;
				if (response != null && response.getLongTime() != null) {
					StoApplication.getStoJni().SetSystemTime(response.getLongTime());
					// jni.SetSystemTime((Long.parseLong(response.getDateTime())+8.5*60*60*1000)+"");
					StoFilePreference.getInstance(
							AdminSystemSettingActivity.this).setTimeSynch(true);
					new DeleteDataThread(AdminSystemSettingActivity.this)
							.start();
					Helper.showLongToast(AdminSystemSettingActivity.this,
							getText(R.string.synch_time_success).toString());
				} else {
					StoFilePreference.getInstance(
							AdminSystemSettingActivity.this)
							.setTimeSynch(false);
					showTimeErrorDialog(getText(R.string.synch_time_failure)
							.toString());
				}
			}
		}

	};
	AlertDialog tdialog = null;

	@SuppressLint("ResourceAsColor")
	private void showTimeErrorDialog(String str) {

		LayoutInflater flater = LayoutInflater.from(this);
		View view = flater.inflate(R.layout.sto_sales_order_notice, null);
		Builder builder = new AlertDialog.Builder(this);

		TextView msgCancelText = (TextView) view
				.findViewById(R.id.order_notice_detailview);

		msgCancelText.setTextColor(Color.WHITE);

		msgCancelText.setText(str);

		builder.setTitle("提示")
				.setView(view)
				.setPositiveButton(R.string.confirm,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
								tdialog = null;
							}
						});

		tdialog = builder.create();
		tdialog.getWindow().setType(
				(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT));
		tdialog.setCancelable(true);
		tdialog.setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				tdialog = null;
			}
		});
		tdialog.show();

	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.admin_system_main);
		broadType = getIntent().getStringExtra(HomeBroadAction.BROAD_TYPE);
		// 判断是管理员的系统设置还是业务内部的系统设置
		if (broadType != null && !broadType.equals("")) {
			this.setTitleBottom(R.string.system_settings, broadType);
		} else {
			this.setTitleBottom(R.string.system_settings,
					HomeBroadAction.ADMINISTRATOR_BROAD);
		}
		initWidget();
		initListener();
	}

	private void initListener() {
		systemList.setOnItemClickListener(new StoOnItemClickListener(this) {

			@Override
			public void KcOnItemClickListener(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				arg1.setSelected(true);
				TextView title = (TextView) arg1.findViewById(R.id.res_test);
				clickItemEvent(title.getText().toString());
			}
		});

	}

	private void clickItemEvent(String string) {
		// 声音
		/*
		 * if (string.equals(getText(R.string.system_sound).toString())) {
		 * Intent intent = new Intent(this, SystemSoundSettingsActivity.class);
		 * if (broadType != null && !broadType.equals("")) {
		 * intent.putExtra(HomeBroadAction.BROAD_TYPE, broadType); } else {
		 * intent.putExtra(HomeBroadAction.BROAD_TYPE,
		 * HomeBroadAction.ADMINISTRATOR_BROAD); } startActivity(intent); } //
		 * 蓝牙设置 else
		 */
		// 触摸屏锁开关
		if (string.equals(getString(R.string.touch_screen_set))) {
			Intent intent = new Intent(this,
					StoTouchScreenLockSetActivity.class);
			if (broadType != null && !broadType.equals("")) {
				intent.putExtra("busiType", broadType);
			} else {
				intent.putExtra(HomeBroadAction.BROAD_TYPE,
						HomeBroadAction.ADMINISTRATOR_BROAD);
			}
			startActivity(intent);
		}
		// 按键音
		else if (string.equals(getText(R.string.keydown_sound).toString())) {
			// Intent intent = new Intent("com.kaicom.keypad.lights");
			// intent.putExtra("com.kaicom.keypad.lights" ,false);
			// sendBroadcast(intent);
			// Helper.showToast(this, "按键音");

			// Intent intent2 = new Intent(KAICOM_DISABLE_BROWSER);
			// intent2.putExtra(KAICOM_DISABLE_BROWSER ,true);
			// sendBroadcast(intent2);
			Intent intent = new Intent(AdminSystemSettingActivity.this,
					SystemKeyMgrActivity.class);
			if (broadType != null && !broadType.equals("")) {
				intent.putExtra("busiType", broadType);
			} else {
				intent.putExtra(HomeBroadAction.BROAD_TYPE,
						HomeBroadAction.ADMINISTRATOR_BROAD);
			}
			startActivity(intent);
		}
		// 系统声音设置
		else if (string.equals(getText(R.string.system_sound_setting))) {
			Intent intent = new Intent(Settings.ACTION_SOUND_SETTINGS);
			startActivity(intent);
		}
		// 自动键盘锁
		else if (string.equals(getText(R.string.system_auto_close_screen)
				.toString())) {
			Intent intent = new Intent(this,
					SystemAutoCloseScreenTimeActivity.class);
			if (broadType != null && !broadType.equals("")) {
				intent.putExtra(HomeBroadAction.BROAD_TYPE, broadType);
			} else {
				intent.putExtra(HomeBroadAction.BROAD_TYPE,
						HomeBroadAction.ADMINISTRATOR_BROAD);
			}
			startActivity(intent);
		} else if (string.equals(getText(R.string.blue_settings).toString())) {
			// Intent intent = new Intent();
			// intent.setAction(Action.BLUETOOTH_ACTION);
			// startActivity(intent);
			Intent intent = new Intent(AdminSystemSettingActivity.this,
					SystemBlueWeigthSettingActivity.class);
			if (broadType != null && !broadType.equals("")) {
				intent.putExtra("busiType", broadType);
			} else {
				intent.putExtra(HomeBroadAction.BROAD_TYPE,
						HomeBroadAction.ADMINISTRATOR_BROAD);
			}
			startActivity(intent);
		}
		// wlan设置
		else if (string.equals(getText(R.string.wlan_settings).toString())) {
			Intent wlanIntent = new Intent();
			wlanIntent.setAction(Action.WLAN_ACTION);
			startActivity(wlanIntent);
		}
		// 使用说明
		else if (string.equals(getText(R.string.direction_for_use).toString())) {
			Intent intent = new Intent(this, SystemUserDeclareActivity.class);
			if (broadType != null && !broadType.equals("")) {
				intent.putExtra(HomeBroadAction.BROAD_TYPE, broadType);
			} else {
				intent.putExtra(HomeBroadAction.BROAD_TYPE,
						HomeBroadAction.ADMINISTRATOR_BROAD);
			}
			startActivity(intent);
		}
		// 异常日志
		else if (string.equals(getText(R.string.exception_log).toString())) {
			Intent intent = new Intent(this, ExceptionLogListActivity.class);
			startActivity(intent);
		}
		// 同步时间
		else if (string.equals(getText(R.string.synch_time).toString())) {
			TimeSynchThread synchThread = new TimeSynchThread(this, handler,
					true);
			synchThread.start();
		}
		// 剩余存储
		else if (string.equals(getText(R.string.surplus_storage).toString())) {
			if(StoConfig.NO_VOID){
				Helper.showToast(this,"未实现");
			}else{
				int mb = 1024 * 1024;
				float systemSurplus = MemorySpaceCheck.getInstance()
						.getSystemAvailableSize() / mb;
				float dataNumber = MemorySpaceCheck.getInstance()
						.getSystemAvailableSize() / 200;
				String byteString = getText(R.string.megabytes_about).toString();
				StringBuffer sb = new StringBuffer();
				sb.append(getText(R.string.current_surplus).toString())
						.append(systemSurplus).append(byteString)
						.append(dataNumber)
						.append(getText(R.string.memory_hint).toString());
				final BaseDialog dialog = new BaseDialog(this);
				dialog.setTitles(sb.toString());
				dialog.show();
				dialog.getvCanncel().setVisibility(View.GONE);
				dialog.getvMessage().setVisibility(View.GONE);
				dialog.getvPresentation().setVisibility(View.GONE);
				dialog.setOnBackClickListener(new OnBackClickListener() {

					@Override
					public void onBackClickListener(boolean res) {
						dialog.dismiss();
					}
				});
			}

		}
		// 软件版本
		else if (string.equals(getText(R.string.version_infomation).toString())) {
			Intent intent = new Intent(this, AdminSoftVersionActivity.class);
			if (broadType != null && !broadType.equals("")) {
				intent.putExtra(HomeBroadAction.BROAD_TYPE, broadType);
			} else {
				intent.putExtra(HomeBroadAction.BROAD_TYPE,
						HomeBroadAction.ADMINISTRATOR_BROAD);
			}
			startActivity(intent);
		}
		// 序列号
		else if (string.equals(getText(R.string.serial_number).toString())) {
			final BaseDialog dialog = new BaseDialog(this);
			dialog.setTitles(StoApplication.getStoJni().GetMachineCode());
			dialog.show();
			dialog.getvCanncel().setVisibility(View.GONE);
			dialog.getvMessage().setVisibility(View.GONE);
			dialog.getvPresentation().setVisibility(View.GONE);
			dialog.setOnBackClickListener(new OnBackClickListener() {

				@Override
				public void onBackClickListener(boolean res) {
					dialog.dismiss();
				}
			});
		}
		// 机器信息
		else if (string.equals(getText(R.string.machine_infomation).toString())) {
			try {
				Intent intent = new Intent();
				intent.setAction(Settings.ACTION_DEVICE_INFO_SETTINGS);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(intent);
			} catch (ActivityNotFoundException ex) {
				ex.printStackTrace();
			}
			/*
			 * 不兼容585 Intent intent = new Intent(); ComponentName name = new
			 * ComponentName( Action.SYSTEM_SETTINGS_PACKAGE,
			 * Action.DEVICE_INFO_SETTINGS); intent.setComponent(name);
			 * startActivity(intent);
			 */
		}
		// 背光
		else if (string.equals(getText(R.string.back_light).toString())) {
			// Helper.showToast(this, "该功能暂未开放");
			Intent intent = new Intent(this, SystemBackLightActivity.class);
			if (broadType != null && !broadType.equals("")) {
				intent.putExtra(HomeBroadAction.BROAD_TYPE, broadType);
			} else {
				intent.putExtra(HomeBroadAction.BROAD_TYPE,
						HomeBroadAction.ADMINISTRATOR_BROAD);
			}
			startActivity(intent);
		}
		// 扫描头设置
		else if (string.equals(getText(R.string.scanner_settings).toString())) {
			// Helper.showToast(this, "该功能暂未开放");
			Intent intent = new Intent(this, SystemScanHeaderActivity.class);
			if (broadType != null && !broadType.equals("")) {
				intent.putExtra(HomeBroadAction.BROAD_TYPE, broadType);
			} else {
				intent.putExtra(HomeBroadAction.BROAD_TYPE,
						HomeBroadAction.ADMINISTRATOR_BROAD);
			}
			startActivity(intent);
		}
		/**
		 * 蓝牙称重设置
		 */
		else if(string.equals(getText(R.string.blue_weight_setting).toString())){

			Intent intent = new Intent(this, SettingBlueWeightActivity.class);
			if (broadType != null && !broadType.equals("")) {
				intent.putExtra(HomeBroadAction.BROAD_TYPE, broadType);
			} else {
				intent.putExtra(HomeBroadAction.BROAD_TYPE,
						HomeBroadAction.ADMINISTRATOR_BROAD);
			}
			startActivity(intent);
		}
		// 软件升级
		else if (string.equals(getText(R.string.software_upgrade).toString())) {
			// startService(new Intent(this, DownloadApkService.class));
			final DownApk downApk = new DownApk(this);
			downApk.startDown();
			downApk.setListener(new ExceptionClickListener() {

				@Override
				public void onExceptionClickListener(final String exception) {
					downApk.dismiss();
					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							Helper.showToast(AdminSystemSettingActivity.this,
									exception);
							// getString(R.string.upgrade_failed));
						}
					});
				}
			});
		}
	}

	private void initWidget() {
		getResoureList();
		systemList = (ListView) findViewById(R.id.system_list);
		soleAdapter = new SoleAdapter(this, functionList);
		systemList.setAdapter(soleAdapter);
	}

	private void getResoureList() {
		functionList = new ArrayList<FunctionEntity>();
		List<String> resList = new ArrayList<String>();
		// resList.add(getText(R.string.system_sound).toString());
		resList.add(getText(R.string.back_light).toString());
		// resList.add(getText(R.string.touch_screen_set).toString());

		// resList.add(getText(R.string.auto_keybroad_lock).toString());
		// resList.add(getText(R.string.change_pwd).toString());
		resList.add(getText(R.string.synch_time).toString());
		resList.add(getText(R.string.system_auto_close_screen).toString());
		resList.add(getText(R.string.surplus_storage).toString());
		// resList.add(getText(R.string.current_version).toString());
		resList.add(getText(R.string.version_infomation).toString());
		resList.add(getText(R.string.software_upgrade).toString());
		resList.add(getText(R.string.blue_settings).toString());
		resList.add(getText(R.string.wlan_settings).toString());
	//	resList.add(getText(R.string.scanner_settings).toString());
		resList.add(getText(R.string.direction_for_use).toString());
		resList.add(getText(R.string.serial_number).toString());
		resList.add(getText(R.string.machine_infomation).toString());
		resList.add(getText(R.string.system_sound_setting).toString());
		resList.add(getText(R.string.scanner_settings).toString());
		resList.add(getText(R.string.blue_weight_setting).toString());
		// resList.add(getText(R.string.debug_settings).toString());system_sound

		for (String res : resList) {
			FunctionEntity entity = new FunctionEntity();
			entity.setTitle(res);
			functionList.add(entity);
		}
	}





	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		handler.removeMessages(MessageType.SYNCH_TIME_TYPE);
		super.onDestroy();
	}

}
